package net.sapfree.display.tags.person;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;

import net.sapfree.common.Constants;
import net.sapfree.core.db.DBConnectionProvider;
import net.sapfree.core.db.DataBaseExecutor;
import net.sapfree.core.db.Record;
import net.sapfree.core.db.RecordSet;
import net.sapfree.display.tags.core.LoopTagSupport;

import org.apache.log4j.Logger;

//查找朋友，按朋友的多少排序
public class FriendIndexListTag extends LoopTagSupport {
	private static Logger log = Logger.getLogger(FriendIndexListTag.class.getClass());
	private RecordSet friendList=null;
	private int count=-1;
	@Override
	protected boolean hasNext() throws JspException {
		return (friendList != null)&&(step<end);
	}

	@Override
	protected Object next() throws JspException {
		Record r=friendList.get(step);
		step++;
		return r;
	}

	 	
	@Override
	protected void prepare() throws JspException {
		ServletRequest request = pageContext.getRequest();
		Connection conn =null;

		try {
			conn = DBConnectionProvider.getConnection(Constants.JNDI_SAPFREE);
			DataBaseExecutor dbe = DataBaseExecutor.getExecutor(conn);
			friendList = dbe.find(getFriendListSql());

			pageContext.setAttribute("FriendIndexListTag", this, PageContext.PAGE_SCOPE);
			end=friendList.size();
		 	step=0;
		} catch (SQLException e) {
			log.error("在执查找朋友列表时出错",e);
		}finally{
			try{
				 conn.close();
			}catch(Exception e){}
		}
	}
	
	private String getFriendListSql(){
		StringBuffer sql = new StringBuffer();
		
		//检索人员的朋友，该人员加的朋友或者别人加该人员两种情况
		sql.append("SELECT COUNT(FR_FRIENDUUID) FRIENDCOUNT,FR_FRIENDUUID FROM FRIENDRELATION GROUP BY FR_FRIENDUUID ORDER BY FRIENDCOUNT DESC" );
		
		if(count!=-1){
			sql.append(" limit 0,").append(count);
		}
		System.out.println(sql.toString());
		return sql.toString();
	}
		
	/**
	 * @return the count
	 */
	public int getCount() {
		return count;
	}

	/**
	 * @param count the count to set
	 */
	public void setCount(int count) {
		this.count = count;
	}

}
